package me.fung.rem.bean.repo

import me.fung.rem.app.encryptor
import me.fung.rem.bean.database
import org.ktorm.dsl.delete
import org.ktorm.dsl.eq
import org.ktorm.dsl.insert
import org.ktorm.ksp.api.PrimaryKey
import org.ktorm.ksp.api.Table

@Table
data class RemItem(
    @PrimaryKey
    val id: Int = 0,
    var title: String = "",
    var username: String = "",
    var password: String = "",
    var info: String = "",
    var address: String = "",
    /**
     * tag : tag1|tag2
     */
    var tag: String = "",
    var del: Boolean = false,
) {

    companion object {
        fun sample(): RemItem = RemItem(
            id = 0,
            title = "",
            username = "",
            password = "",
            info = "",
            address = "",
            tag = "",
        )
    }
}

fun RemItem.tags(): List<String> {
    return tag.split("|").filter { it.isNotBlank() }
}

fun Collection<String>.tag(): String {
    return joinToString("|")
}

fun RemItem.modify() {
    val encryptor = encryptor()
    database.remItems.update(copy(password = encryptor.encrypt(password)))
}

fun RemItem.add() {
    val encryptor = encryptor()
    database.insert(RemItems) {
        set(it.title, title)
        set(it.username, username)
        set(it.password, encryptor.encrypt(password))
        set(it.info, info)
        set(it.address, address)
        set(it.tag, tag)
        set(it.del, del)
    }
}

fun RemItem.delete() {
    database.delete(RemItems) {
        it.id eq id
    }
}